package com.lagou.controller;

import com.lagou.pojo.AuthToken;
import com.lagou.service.UserService;
import com.lagou.vo.Result;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: UserController
 * @Auther: Jerry
 * @Date: 2020/10/22 17:16
 * @Desctiption: TODO
 * @Version: 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @RequestMapping("/register/{email}/{password}/{code}")
    @ResponseBody
    public Boolean register(@PathVariable("email") String email,
                            @PathVariable("password") String password,
                            @PathVariable("code") String code) {
        return userService.register(email, password, code);
    }

    @RequestMapping("/isRegistered/{email}")
    @ResponseBody
    public Boolean isRegistered(@PathVariable("email") String email) {
        return userService.isRegistered(email);
    }


    @RequestMapping("/login/{email}/{password}")
    @ResponseBody
    public String login(HttpServletResponse response, @PathVariable("email") String email,
                        @PathVariable("password") String password) {
        Result<AuthToken> result = userService.login(email, password);
        if (result != null) {
            Cookie cookie = new Cookie("lg_token",result.getData().getToken());
            cookie.setMaxAge(3600);
            cookie.setPath("/");
            response.addCookie(cookie);
            return result.getData().getEmail();
        }
        return null;
    }

    @RequestMapping("/info/{token}")
    @ResponseBody
    public String info(@PathVariable("token") String token) {
        Result<AuthToken> info = userService.info(token);

        return info.getData() == null ? null : info.getData().getEmail();
    }

}
